#include <cstdlib>
#include <iostream>
#include <memory>
#include <alibabacloud/core/AlibabaCloud.h>
#include <alibabacloud/core/CommonRequest.h>
#include <alibabacloud/core/CommonClient.h>
#include <alibabacloud/core/CommonResponse.h>
#include "Logger.hpp"

namespace XKL
{
    class DMSClient
    {
    public:
        DMSClient(const std::string &access_key_id, const std::string &access_key_secret)
        {
            AlibabaCloud::InitializeSdk();
            AlibabaCloud::ClientConfiguration configuration("cn-hangzhou");
            configuration.setConnectTimeout(1500);
            configuration.setReadTimeout(4000);
            std::string access_key_id = access_key_id;
            std::string access_key_secret = access_key_secret;
            AlibabaCloud::Credentials credential(access_key_id, access_key_secret);
            _client = std::make_unique<AlibabaCloud::CommonClient>(credential, configuration);
        }

        bool send(const std::string &phone, const std::string &code)
        {
            AlibabaCloud::CommonRequest request(AlibabaCloud::CommonRequest::RequestPattern::RpcPattern);
            request.setHttpMethod(AlibabaCloud::HttpRequest::Method::Post);
            request.setDomain("dysmsapi.aliyuncs.com");
            request.setVersion("2017-05-25");
            request.setQueryParameter("Action", "SendSms");
            request.setQueryParameter("SignName", "IM系统");
            request.setQueryParameter("TemplateCode", "SMS_474921135");
            request.setQueryParameter("PhoneNumbers", phone);
            std::string param_code = "{\"code\":\"" + code + "\"}";
            request.setQueryParameter("TemplateParam", "{\"code\":\"1234\"}");

            auto response = _client->commonResponse(request);
            if (!response.isSuccess())
            {
                LOG_ERROR("Failed to send SMS verification code: {}", response.error().errorMessage());
                return false;
            }
            return true;
        }
        ~DMSClient()
        {
            AlibabaCloud::ShutdownSdk();
        }

    private:
        std::unique_ptr<AlibabaCloud::CommonClient> _client;
    };
}